﻿namespace TomatoBreak.Infrastructure
{
    using System;
    using System.Collections.Generic;

    using ExtensionMethods;

    public class TypeMappingRegistry<TType1, TType2>
    {
        public TypeMappingRegistry() : this(new Dictionary<Type, Type>())
        {
        }

        protected TypeMappingRegistry(IDictionary<Type, Type> backingStore)
        {
            if (backingStore == null)
            {
                throw new ArgumentNullException("backingStore");
            }

            BackingStore = backingStore;
        }

        protected IDictionary<Type, Type> BackingStore { get; private set; }

        public virtual bool IsRegistered(Type type)
        {
            return BackingStore.ContainsKey(type);
        }

        public virtual void Register(Type type1, Type type2)
        {
            EnsureType(typeof(TType1), type1, "type1");
            EnsureType(typeof(TType2), type2, "type2");

            BackingStore.Add(type1, type2);
        }

        public virtual Type Matching(Type type)
        {
            return IsRegistered(type) ? BackingStore[type] : null;
        }

        private static void EnsureType(Type parent, Type child, string parameterName)
        {
            if (!parent.IsAssignableFrom(child))
            {
                throw new ArgumentException(Web.ErrorMessages.TypeMappingRegistry_EnsureType_IncorrectType.Interpolate(child.Name, parent.Name), parameterName);
            }
        }
    }
}